// 1、部署合约到Ropsten测试网络
const path = require('path');
const Web3 = require('web3');
const fs = require('fs');

const HDWalletProvider = require('truffle-hdwallet-provider');


//CourseList的绝对路径
const contractPath = path.resolve(path.resolve(__dirname, '../src/compiled/CourseList.json'));
// console.log(contractPath);
const {interface, bytecode} = require(contractPath);

// HDWalletProvider(
//  matemask助记词,
//  "infura 提供的地址"
// );
const provider = new HDWalletProvider(
    "uniform reason ability robust essay minute usual detail burger forest cook atom",
    "https://ropsten.infura.io/v3/bed21147da1a4850af1a261fffe5c9b6"
);
const web3 = new Web3(provider);


(async () => {
    // console.log('自执行函数');
    const account = await  web3.eth.getAccounts();
    console.log('合约部署的账号：', account);
    console.time('部署合约消耗时间');
    // 注意：此处出现了得出的account账号与matemask账号不一致的情况，实际上账号是根据助记词做hash生成的，所以如果助记词随便写也能生成地址
    // 此处使用助记词重置密码之后，account才一致（可能账号已经是另一个账号了）
    //  部署账号地址 0x5c7463fecFEC02d857c1D69Ed205eb21c58453b1

    const result = await  new web3.eth.Contract(JSON.parse(interface))
        .deploy({data: bytecode})
        .send({
            from:account[0],
            gas:'5000000'
        });
    console.timeEnd('部署合约消耗时间');
    console.log(result.options);
    const contractAddress = result.options.address;
    console.log('合约部署成功', contractAddress);
    console.log('合约查看地址', `https:ropsten.etherscan.io/address/${contractAddress}`);


    const addressFile = path.resolve(path.resolve(__dirname, '../src/address.js'));
    fs.writeFileSync(addressFile, "export default " + JSON.stringify(contractAddress));
    console.log("地址写入成功", addressFile);

    // 合约地址在
    // https://ropsten.etherscan.io/address/0xf0E6C405851e239E886563Ee5b6Df8CCf628178E
    // 可以看到，也可以查看合约被调用的信息等

})();

